package com.example.kingdee;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.example.kingdee.common.AjaxResult;
import com.example.kingdee.exception.HintException;
import com.example.kingdee.exception.ProcedureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

//    @ExceptionHandler(value = NullPointerException.class)
//    public AjaxResult sqlHandleException(Exception e) {
//        log.error(e.getMessage(), e);
//        return AjaxResult.error(e.getMessage());
//    }

    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(getErrMsg());
    }

    //数据库处理错误处理
    @ExceptionHandler(DataAccessException.class)
    public AjaxResult handleException(DataAccessException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(getErrMsg());
    }

    //运行时异常处理
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(getErrMsg());
    }

    //提示性异常处理
    @ExceptionHandler(HintException.class)
    public AjaxResult handleException(HintException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.hint(e.getMessage());
    }

    //手动捕获异常处理
    @ExceptionHandler(ProcedureException.class)
    public AjaxResult handleException(ProcedureException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    private String getErrMsg(){
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String err = "系统内部错误，日志id：{}";
        return StrUtil.format(err, date);
    }

}
